<template>
  <div class="user-container">
    <div class="button-container">
      <el-button type="primary" size="small" @click="dialogFormVisible = true">添加用户</el-button>
      <el-button type="danger" size="small" @click="DeleteUser">批量删除</el-button>
      <el-input style="width: 250px;margin-left: 50px;" size="small" placeholder="请输入用户昵称" prefix-icon="el-icon-search"
        v-model="user.nickname" clearable @clear="getUserList">
        <el-button size="small" slot="append" icon="el-icon-search" @click="getUserList"></el-button>
      </el-input>

    </div>
    <div class="table-container">
      <el-table :data="userList" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="50">
        </el-table-column>
        <el-table-column type="index" label="序号" width="60">
        </el-table-column>
        <el-table-column prop="username" label="账号" width="120">
        </el-table-column>
        <el-table-column prop="nickname" label="昵称" width="120">
        </el-table-column>
        <el-table-column prop="phone" label="电话" width="120">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="180">
        </el-table-column>
        <el-table-column prop="avatar" label="头像" width="80">
          <template slot-scope="scope">
            <img :src="scope.row.avatar" class="avatar-img">
          </template>
        </el-table-column>
        <el-table-column prop="password" label="密码" width="120">
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="200">
          <template slot-scope="scope">
            <el-button @click="handleDetail(scope.row)" type="text" size="large">查看</el-button>
            <el-button @click="handleUpdate(scope.row)" type="text" size="large">编辑</el-button>
            <el-button @click="handleDelete(scope.row)" type="text" size="large">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="block">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="user.pageNum"
        :page-sizes="[5, 10, 20, 50]" :page-size="user.pageSize" layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
    <!-- 详情窗口 -->
    <div class="dialog-container">
      <el-dialog :visible.sync="dialogTableVisible" width="400px" @close="closeDialog">
        <el-descriptions title="用户信息" :column=2>
          <el-descriptions-item label="账号">{{ form.username }}</el-descriptions-item>
          <el-descriptions-item label="密码">{{ form.password }}</el-descriptions-item>
          <el-descriptions-item label="昵称">{{ form.nickname }}</el-descriptions-item>
          <el-descriptions-item label="邮箱">{{ form.email }}</el-descriptions-item>
          <el-descriptions-item label="电话">{{ form.phone }}</el-descriptions-item>
          <el-descriptions-item label="角色">
            <el-tag size="small">{{ form.role }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="头像">
            <p style="display: flex;justify-content: center;align-items: center;">
              <img v-if="form.avatar" :src="form.avatar" class="avatar">
            </p>
          </el-descriptions-item>
        </el-descriptions>
      </el-dialog>

      <!-- 添加、编辑窗口 -->
      <el-dialog :title="form.id ? '编辑用户' : '新增用户'" width="400px" :visible="dialogFormVisible" :show-close="false">
        <el-form :rules="rules" ref="form" label-width="55px" :model="form">
          <el-form-item style="margin-bottom: 0px;display: flex; justify-content: center ;align-items: center;">
            <el-upload class="avatar-uploader" action="#" :http-request="uploadRequest" :show-file-list="false"
              :before-upload="beforeAvatarUpload">
              <img v-if="form.avatar" :src="form.avatar" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
          <el-form-item label="账号" prop="username">
            <el-input style="width: 300px;" clearable size="small" v-model="form.username"
              autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input style="width: 300px;" clearable size="small" v-model="form.password"
              autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input style="width: 300px;" clearable size="small" v-model="form.email" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="昵称" prop="nickname">
            <el-input style="width: 300px;" clearable size="small" v-model="form.nickname"
              autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="phone">
            <el-input style="width: 300px;" clearable size="small" v-model="form.phone" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button size="small" @click="cancel">取 消</el-button>
          <el-button size="small" @click="resetForm">重置</el-button>
          <el-button size="small" type="primary" @click="addUser">确 定</el-button>
        </div>
      </el-dialog>
    </div>

  </div>
</template>

<script>
import { getUserListAPI, addUserAPI, updateUserAPI, getUserDetailAPI, deleteUserAPI } from '@/api/userManage'
import { upload } from '@/api/web'
export default {
  data() {
    return {
      form: {
        id: '',
        username: '',
        password: '',
        email: '',
        nickname: '',
        avatar: '',
        phone: ''
      },
      user: {
        pageNum: 1,
        pageSize: 5,
        username: '',
        nickname: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' }
        ],
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          { min: 11, max: 11, message: '输入11个数字', trigger: 'change' }
        ],
      },
      ids: "",
      total: 0,
      userList: [],
      dialogFormVisible: false,
      dialogTableVisible: false
    }
  },
  mounted() {
    this.getUserList()
  },
  methods: {
    // 上传文件
    async uploadRequest(data) {
      const file = data.file
      // 处理formData类型参数
      const formData = new FormData()
      formData.append('file', file)
      const res = await upload(formData)
      if(res.code ==='200'){
        this.$message.success("上传成功")
        this.form.avatar = res.data
      }else{
        this.$message.error("上传失败")
      }
    },
    // 上传文件前检查
    beforeAvatarUpload(file) {
      const isJPGandPNG = (file.type === 'image/jpeg') || (file.type === 'image/png');
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPGandPNG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPGandPNG && isLt2M;
    },

    closeDialog() {
      this.form.id = ''
      this.form.username = ''
      this.form.password = ''
      this.form.email = ''
      this.form.nickname = ''
      this.form.avatar = ''
      this.form.phone = ''
    },
    // 重置按钮
    resetForm() {
      this.closeDialog()
      this.$refs.form.clearValidate();
    },
    // 取消按钮
    cancel() {
      this.resetForm()
      this.dialogFormVisible = false
      this.getUserList()
    },
    // 处理分页
    handleSizeChange(val) {
      this.user.pageSize = val
      this.getUserList()
    },
    handleCurrentChange(val) {
      this.user.pageNum = val
      this.getUserList()
    },
    //获取列表
    async getUserList() {
      const res = await getUserListAPI(this.user)
      this.total = res.data.total
      this.userList = res.data.rows
    },
    // 添加用户
    addUser() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          if (this.form.id) {
            const res = await updateUserAPI(this.form)
            if (res.code == 200) {
              this.$message.success("编辑成功")
              this.cancel()
            } else {
              this.$message.error(res.msg)
            }
          } else {
            const res = await addUserAPI(this.form)
            if (res.code == 200) {
              this.$message.success("添加成功")
              this.cancel()
            } else {
              this.$message.error(res.msg)
            }
          }
        }
      });
    },
    // 用户详情
    async handleDetail(row) {
      this.dialogTableVisible = true
      const res = await getUserDetailAPI(parseInt(row.id))
      this.form.username = res.data.username
      this.form.password = res.data.password
      this.form.email = res.data.email
      this.form.nickname = res.data.nickname
      this.form.avatar = res.data.avatar
      this.form.phone = res.data.phone
      this.form.role = res.data.role
    },
    // 删除用户
    handleDelete(row) {
      this.ids = row.id
      this.DeleteUser()
    },
    handleSelectionChange(val) {
      this.ids = val.map(item => item.id);
    },
    DeleteUser() {
      this.$confirm("你确定要删除吗？").then(async () => {
        const res = await deleteUserAPI(this.ids)
        this.getUserList()
        if (res.code == 200) {
          this.$message.success("删除成功")
          this.pageNum = 1
        } else {
          this.$message.error("删除失败")
        }
      }).catch(() => {
        this.$message.info("已取消")
      })
    },
    // 修改用户信息
    async handleUpdate(row) {
      this.dialogFormVisible = true,
        this.form.id = row.id
      this.form.username = row.username
      this.form.password = row.password
      this.form.email = row.email
      this.form.nickname = row.nickname
      this.form.avatar = row.avatar
      this.form.phone = row.phone
    },
  }
}
</script>

<style>
.button-container {
  margin: 10px;
}

.el-table .el-table__cell {
  padding: 5px 0 5px 0;
}

.avatar-img {
  width: 45px;
  height: 45px;
  border-radius: 50%;
}

.block {
  text-align: right;
  padding: 10px;
}

.el-form-item {
  margin-bottom: 12px;
}

.el-dialog__body {
  padding: 0 20px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.el-form-item__content {
  margin-left: 0px !important;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.el-dialog__header {
  padding: 20px 20px 0;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}

.el-message-box {
  width: 300px;
}
</style>
@/api/userManage